package com.windoent.yugioh.ui.activity.saishi;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.SearchBaomingJudgeAdapter;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.CaiPanListSearchData;
import com.windoent.yugioh.bean.GeneralBean;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.SearchView;
import com.windoent.yugioh.widget.dialog.ExitGameReasonDialog;
import com.windoent.yugioh.widget.dialog.SucessFailAutoDismissDialog;
import com.windoent.yugioh.widget.dialog.SureNotDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.util.List;

import okhttp3.Call;


/**
 * author : robert
 * date   : 2021/5/19 17:31
 * desc   :搜索报名裁判
 */
public class SearchBaoMingCaiPanActivity extends BaseActivity {
    private View mView;
    private LinearLayout mBack;
    private SearchView mSearch;
    private SmartRefreshLayout mSmartLayout;
    private RecyclerView mRecyclerView;
    private SearchBaomingJudgeAdapter mAdapter;
    private String limit = Constants.PAGETEN;
    private int mCount = 1;
    private String id = "";
    private String text = "";

    @Override
    public int getLayout() {
        return R.layout.activity_saishi_baoming_ing_auth_caipan_search;
    }

    @Override
    public void initView() {
        super.initView();

        mView = (View) findViewById(R.id.view);
        immersiveStatusBar(mView);
        mBack = (LinearLayout) findViewById(R.id.ll_back);
        mSearch = (SearchView) findViewById(R.id.search);
        mSmartLayout = (SmartRefreshLayout) findViewById(R.id.smart_layout);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    }

    @Override
    public void initData() {
        super.initData();
        id = getIntent().getStringExtra("id");
        initAdapter();
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new SearchBaomingJudgeAdapter();
        mAdapter.setEmptyView(LayoutInflater.from(mContext).inflate(R.layout.recycler_view_empty, mRecyclerView, false));
        mAdapter.setAnimationEnable(false);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                List<CaiPanListSearchData.DataBean.MergeRefereeBean> data = mAdapter.getData();
                if (data != null) {
                    CaiPanListSearchData.DataBean.MergeRefereeBean mergeRefereeBean = data.get(position);
                    if (mergeRefereeBean != null) {
                        int statusId = mergeRefereeBean.getStatusId();
                        if (statusId == 1) {
                            //通过
                            int uid = mergeRefereeBean.getId();
                            showAuthDialog(uid, mergeRefereeBean.getType() + "");
                        } else if (statusId == 2) {
                            int userID = mergeRefereeBean.getUid();
                            showExitJudgeDialog(userID);
                        }
                    }
                }
            }
        });
    }

    //踢出裁判
    private void showExitJudgeDialog(int userID) {
        SureNotDialog dialog = new SureNotDialog(mContext);
        dialog.setTvContent(getString(R.string.string_sure_exit_judge_games_warn));
        dialog.setYesStr(getString(R.string.string_sure));
        dialog.setNoStr(getString(R.string.dl_cancel));
        dialog.setYesOnclickListener(new SureNotDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                showExitReason(userID);
            }
        });
        dialog.show();
    }

    private void showExitReason(int userID) {
        ExitGameReasonDialog dialog = new ExitGameReasonDialog(mContext);
        dialog.setOnclickListener(new ExitGameReasonDialog.onClickListener() {
            @Override
            public void onClick(String string) {
                dianjiaExitCaiPan(id, userID, string);
            }
        });
        dialog.show();
    }

    //店家退出裁判
    private void dianjiaExitCaiPan(String id, int userID, String remark) {
        showLoadingDialog("");
        PhoneLive.dianjiaExitCaiPan(getUserToken(), id, userID, remark, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int responseId) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_exit_judge_sucess)), new SucessFailAutoDismissDialog.OnInterface() {
                                @Override
                                public void onDissmiss() {
                                    //刷新列表
                                    initRefreshData(text);
                                    fresh(text);
                                }
                            });
                        } else {
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_exit_judge_fail), BaseMethod.notNullDefaultValueNull(msg));
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //审核通过
    private void showAuthDialog(int userID, String type) {
        SureNotDialog dialog = new SureNotDialog(mContext);
        dialog.setTvContent(getString(R.string.string_sure_auth_pass_warn));
        dialog.setYesOnclickListener(new SureNotDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                dianjiaPassCaiPan(id, userID, type);
            }
        });
        dialog.show();
    }

    //店家审核通过裁判
    private void dianjiaPassCaiPan(String id, int userID, String type) {
        showLoadingDialog("");
        PhoneLive.dianjiaPassCaiPan(getUserToken(), id, userID, type, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int rid) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_sppaly_judge_sucess)), new SucessFailAutoDismissDialog.OnInterface() {
                                @Override
                                public void onDissmiss() {
                                    initRefreshData(text);
                                    fresh(text);
                                }
                            });
                        } else {
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_sppaly_judge_fail), BaseMethod.notNullDefaultValueNull(msg));
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }

            }
        });
    }

    @Override
    public void initListener() {
        super.initListener();
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mSearch.getEditText().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH || i == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    //此处做逻辑处理
                    text = mSearch.getEditStr();
                    initRefreshData(text);
                    fresh(text);
                    return true;
                }
                return false;
            }
        });
    }

    private void initRefreshData(String text) {
        //下拉刷新
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(text);
            }
        });
        //加载更多
        mSmartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore(text);
            }
        });
    }

    private void loadMore(String text) {
        mCount = mCount + 1;
        getListData(text, mCount + "", limit, false);
    }

    private void fresh(String text) {
        mCount = 1;
        getListData(text, mCount + "", limit, true);
    }

    //审核裁判列表搜索
    private void getListData(String title, String page, String limit, boolean fresh) {
        showLoadingDialog("");
        PhoneLive.searchCaiPanListData(getUserToken(), id, title, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                freshFail(fresh);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            CaiPanListSearchData fromJson = gson.fromJson(response, CaiPanListSearchData.class);
                            if (fromJson != null) {
                                CaiPanListSearchData.DataBean data = fromJson.getData();
                                if (data != null) {
                                    List<CaiPanListSearchData.DataBean.MergeRefereeBean> mergeReferee = data.getMergeReferee();
                                    if (mergeReferee != null) {
                                        if (fresh) {
                                            mSmartLayout.finishRefresh(true);
                                            mAdapter.setNewInstance(mergeReferee);
                                        } else {
                                            mSmartLayout.finishLoadMore(true);
                                            mAdapter.addData(mergeReferee);
                                        }
                                    } else freshFail(fresh);
                                } else freshFail(fresh);
                            } else freshFail(fresh);
                        } else freshFail(fresh);
                    } catch (JSONException e) {
                        freshFail(fresh);
                        e.printStackTrace();
                    }
                } else {
                    freshFail(fresh);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //刷新失败
    private void freshFail(boolean fresh) {
        if (fresh) {
            //adapter.setNewInstance(null);
            mSmartLayout.finishRefresh(false);
        } else {
            mSmartLayout.finishLoadMore(false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "赛事搜索报名裁判界面");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "赛事搜索报名裁判界面");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }
}
